odoo.define('selection_many2one', function (require) {
    "use strict";
    var fields = require('web.relational_fields');
    var fieldRegistry = require('web.field_registry');
    var core = require('web.core');
    var _t = core._t;
    var FieldMany2One = fields.FieldMany2One;

    var Selection_FieldMany2One = FieldMany2One.extend({
        _bindAutoComplete: function () {
            var self = this;
            if ($.browser.chrome && this.$input.attr('placeholder')) {
                this.$input.attr('placeholder', function (index, val) {
                    return val.split('').join('\ufeff');
                });
            }
            this.$input.autocomplete({
                source: function (req, resp) {
                    _.each(self._autocompleteSources, function (source) {
                        // Resets the results for this source
                        source.results = [];

                        // Check if this source should be used for the searched term
                        if (!source.validation || source.validation.call(self, req.term)) {
                            source.loading = true;

                            // Wrap the returned value of the source.method with a promise
                            // So event if the returned value is not async, it will work
                            Promise.resolve(source.method.call(self, req.term)).then(function (results) {
                                source.results = results;
                                source.loading = false;
                                resp(self._concatenateAutocompleteResults());
                            });
                        }
                    });
                },
                select: function (event, ui) {
                    // we do not want the select event to trigger any additional
                    // effect, such as navigating to another field.
                    event.stopImmediatePropagation();
                    event.preventDefault();

                    var item = ui.item;
                    self.floating = false;
                    if (item.id) {
                        self.reinitialize({id: item.id, display_name: item.name});
                    } else if (item.action) {
                        item.action();
                    }
                    return false;
                },
                focus: function (event) {
                    event.preventDefault(); // don't automatically select values on focus
                },
                open: function (event) {
                    self._onScroll = function (ev) {
                        if (ev.target !== self.$input.get(0) && self.$input.hasClass('ui-autocomplete-input')) {
                            self.$input.autocomplete('close');
                        }
                    };
                },
                close: function (event) {
                    if (event.which === $.ui.keyCode.ESCAPE) {
                        event.stopPropagation();
                    }
                },
                autoFocus: true,
                html: true,
                minLength: 0,
                delay: this.AUTOCOMPLETE_DELAY,
            });
            this.$input.autocomplete("option", "position", {my: "left top", at: "left bottom"});
            this.autocomplete_bound = true;
            this.$input.autocomplete("widget").css('max-height', '350px')
            this.$input.autocomplete("widget").css('overflow', 'hidden')
            this.$input.autocomplete("widget").css('overflow-y', 'scroll')
        },
        _search: function (search_val) {
            var self = this;
            var def = new Promise(function (resolve, reject) {
                var context = self.record.getContext(self.recordParams);
                var domain = self.record.getDomain(self.recordParams);
                self.limit = 100;
                _.extend(context, self.additionalContext);

                var blacklisted_ids = self._getSearchBlacklist();
                if (blacklisted_ids.length > 0) {
                    domain.push(['id', 'not in', blacklisted_ids]);
                }

                self._rpc({
                    model: self.field.relation,
                    method: "name_search",
                    kwargs: {
                        name: search_val,
                        args: domain,
                        operator: "ilike",
                        context: context,
                    }
                }).then(function (result) {
                    var values = _.map(result, function (x) {
                        x[1] = self._getDisplayName(x[1]);
                        return {
                            label: _.str.escapeHTML(x[1].trim()) || data.noDisplayContent,
                            value: x[1],
                            name: x[1],
                            id: x[0],
                        };
                    });

                    var create_enabled = self.can_create && !self.nodeOptions.no_create;
                    var raw_result = _.map(result, function (x) {
                        return x[1];
                    });
                    if (create_enabled && !self.nodeOptions.no_quick_create &&
                        search_val.length > 0 && !_.contains(raw_result, search_val)) {
                    }
                        if (values.length === 0) {
                        values.push({
                            label: _t("No results to show..."),
                        });
                    }

                    resolve(values);
                });
            });
            this.orderer.add(def);
            return def;
        },
    })

    fieldRegistry.add('selection_many2one', Selection_FieldMany2One);

});